import { getToken } from "@/utils/auth";
import { route } from "./socketRoute";

let socket;
let reconnectInterval = 1000;
const url = "wss://api.aipanpan.shop/ws";
// const url = 'ws://192.168.10.10:8199/ws'
let shouldReconnect = true; // 控制重连的标志
async function connect() {
  if (!getToken()) {
    return;
  }
  let token = `${getToken()}`;
  if (!socket) {
    try {
      socket = new WebSocket(url, [token]);
      socket.onopen = async () => {
        socket.send("hello");
        reconnectInterval = 1000; // 重置重连间隔
        // await wait(5000)
      };
      socket.onmessage = (event) => {
        console.log("Received from server:", event.data);
        console.log();
        route(JSON.parse(event.data));
      };
      socket.onclose = () => {
        console.log("Disconnected from server");
        if (shouldReconnect) {
          reconnect();
        }
      };
      socket.onerror = (event) => {
        console.log("WebSocket Error:", event.error);
        if (shouldReconnect) {
          socket.close();
        }
      };
    } catch (err) {
      console.log(err);
    }
  } else {
    switch (socket.readyState) {
      case socket.CONNECTING: //表示正在连接。
        console.log("正在连接");
        break;
      case socket.OPEN: //表示连接成功，可以通信了。
        console.log("已经连接");
        break;
      case socket.CLOSING: //表示连接正在关闭。
        console.log("正在关闭,1秒后再次尝试连接");
        setTimeout(() => {
          reconnect();
        }, 1000);
        break;
      case socket.CLOSED: //表示连接已经关闭，或者打开连接失败
        console.log("已经关闭,再次连接");
        socket = null;
        reconnect();
        break;
      default:
        // this never happens
        break;
    }
  }
}

function reconnect() {
  console.log(
    `Attempting to reconnect in ${reconnectInterval / 1000} seconds...`
  );
  setTimeout(() => {
    reconnectInterval = Math.min(reconnectInterval * 2, 30000); // 增加重连间隔，但不超过30秒
    connect();
  }, reconnectInterval);
}

function closeConnection() {
  shouldReconnect = false; // 禁止自动重连
  if (socket) {
    socket.close();
  }
  console.log("Connection closed manually");
}

// 函数实现，参数单位 毫秒 ；
function wait(ms) {
  return new Promise((resolve) => setTimeout(() => resolve(), ms));
}

export { connect, closeConnection };
